package cn.cellcom.agent.online.iq.visitor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.biz.TChannelBiz;
import cn.cellcom.agent.biz.TGroupBiz;
import cn.cellcom.agent.online.client.Client;
import cn.cellcom.agent.online.client.VisitorClient;
import cn.cellcom.agent.online.iq.AbstractChainedProcessor;
import cn.cellcom.agent.online.iq.Processor;
import cn.cellcom.agent.online.iq.ProcessorResult;
import cn.cellcom.agent.online.message.MessageConstant.MESSAGE_EVENT;
import cn.cellcom.agent.online.wrapper.SessionWrapper;
import cn.cellcom.agent.struts.form.VisitorForm;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.util.AU;
import cn.cellcom.jar.util.MyException;

public class GetGroupListProcessor extends AbstractChainedProcessor {

	public static final String NAME = MESSAGE_EVENT.GET_GROUP.name();

	private Logger log = LoggerFactory.getLogger(this.getClass());

	public GetGroupListProcessor(Processor next) {
		super(next);
	}

	@Override
	public ProcessorResult doProcess(Map<String, AbstractBiz> bizs, Client client, VisitorForm cf) {
		Map<String, Object> map = new HashMap<String, Object>();

		VisitorClient vc = (VisitorClient) client;
		SessionWrapper session = vc.getSessionByPid(cf.getPid());
		if (session == null) {
			log.error("[{}] get group list for channel[{}] in pid[{}], but the session is null.", client.getId(), cf.getChannel(), cf.getPid());
			return new ProcessorResult(false, this, map);
		}
		TGroupBiz gbiz = (TGroupBiz) bizs.get("gbiz");
		TChannelBiz chbiz = (TChannelBiz) bizs.get("chbiz");
		try {
			List list = chbiz.getRouteGroupsByNo(cf.getPid(), vc.getChannel());
			if(AU.isBlank(list)) {
				list = gbiz.getGroupList(cf.getPid());
			}
			map.put("list", list);
			//把推送的信息写入第一个元素
			if (StringUtils.isNotBlank(session.getSetting().getBeforeGroupList())) {
				map.put("title", session.getSetting().getBeforeGroupList());
			} else {
				map.put("title", "");
			}
		} catch (MyException e) {
			log.error("[{}] get group list for pid[{}] fail ", client.getId(), cf.getPid(), e.getException());
		}
		log.info("[{}] get group list for channel[{}] in pid[{}]", client.getId(), cf.getChannel(), cf.getPid());
		return new ProcessorResult(true, this, map);
	}

	@Override
	public boolean isAcceptable(VisitorForm message) {
		return NAME.equals(message.getEvent());
	}
}
